package com.atguigu.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.yygh.cmn.client.DictFeignClient;
import com.atguigu.yygh.hosp.repository.HospitalRepository;
import com.atguigu.yygh.hosp.service.HospitalService;
import com.atguigu.yygh.model.hosp.Hospital;
import com.atguigu.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author study
 * @version 1.0
 * @date 2021/5/7 16:32
 */
@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;

    @Autowired
    private DictFeignClient dictFeignClient;

    @Override
    public void save(Map<String, Object> stringObjectMap) {
        //MAP 转为 对象
        final String o = JSONObject.toJSONString(stringObjectMap);
        final Hospital hospital = JSONObject.parseObject(o, Hospital.class);

        final String hoscode = hospital.getHoscode();
        //判断是否存在数据
        final Hospital hospitalByHoscode = hospitalRepository.getHospitalByHoscode(hoscode);
        if (hospitalByHoscode != null) {
            hospital.setStatus(hospitalByHoscode.getStatus());
            hospital.setCreateTime(hospitalByHoscode.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            hospital.setId(hospitalByHoscode.getId());
            hospitalRepository.save(hospital);
            return;
        }
        hospital.setStatus(0);
        hospital.setCreateTime(new Date());
        hospital.setUpdateTime(new Date());
        hospital.setIsDeleted(0);
        hospitalRepository.save(hospital);
        //如果不存在，进行添加
    }

    @Override
    public Page selectHospPage(Integer page, Integer limit, HospitalQueryVo vo) {
        Pageable pageable = PageRequest.of(page - 1, limit);
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase(true);

        //HospitalQueryVo 转 Hospital
        final Hospital hospital = new Hospital();
        BeanUtils.copyProperties(vo, hospital);
        Example<Hospital> example = Example.of(hospital, matcher);
        final Page<Hospital> pages = hospitalRepository.findAll(example, pageable);
        final List<Hospital> content = pages.getContent();
        content.stream().forEach(hospital1 -> {
            this.setHospitalHosType(hospital1);
        });

        return pages;
    }

    private Hospital setHospitalHosType(Hospital hospital1) {
        final String hostype = dictFeignClient.getName("Hostype", hospital1.getHostype());
        hospital1.getParam()
                .put("hostypeString", hostype);
        return hospital1;
    }
}
